package logic

import (
	"cartsrv/models/mysql"
	"cartsrv/models/redisinit"
	"context"
	"errors"

	"cartsrv/cartrpc"
	"cartsrv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cartrpc.AddCartRequest) (*cartrpc.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.CartInfo(int(in.GoodsId))
	if err != nil {
		logx.Error("商品不存在")
		return nil, err
	}
	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}

	if g.GoodsStock < int(in.GoodsNum) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}
	redisinit.AddCart(int(in.UserId), int(in.GoodsId), int(in.GoodsNum), g.GoodsTitle, g.GoodsCover, float32(g.GoodsPrice))
	return &cartrpc.AddCartResponse{}, nil
}
